<template>
    <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
        textAlign: 'center',
        background: '#f5f7fa',
        fontWeight: 'bold',
        position: 'sticky',
        top: 0
    }" :span-method="objectSpanMethod">
        <!-- <el-table-column fixed width="180px" prop="sale_outbound_code" label="销售出库订单编号" /> -->
        <el-table-column fixed width="180px" prop="sale_outbound_code" label="销售出库订单编号">
            <template #default="scope">
                <el-link type="primary" @click="infoPage(scope.row.sale_outbound_code)">{{ scope.row.sale_outbound_code
                    }}</el-link>
            </template>
        </el-table-column>
        <el-table-column fixed width="180px" prop="sale_outbound_status" label="订单状态" />
        <el-table-column prop="customer_name" label="客户名称" width="180px" />
        <el-table-column prop="sale_order_name" label="订单名称" width="180px" />
        <el-table-column prop="pro_name" label="产品名称" width="150px" />
        <el-table-column prop="pro_code" label="产品编号" width="180px" />
        <el-table-column prop="pro_brand" label="品牌" width="150px" />
        <el-table-column prop="pro_model" width="180px" label="规格型号" />
        <el-table-column prop="measure_id" label="单位">
            <template #default="scope">
                <span>{{ measureValue(scope.row.measure_id) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="pro_sale_qty" width="100px" label="销售数量" />
        <el-table-column prop="pro_awaiting_dispatch_qty" label="待出库数量" width="150px" />
        <el-table-column prop="pro_current_shipment_qty" label="出库数量" width="150px" />
        <el-table-column prop="dispatch_qty" label="待出库总数量" width="150px" />
        <el-table-column prop="shipment_qty" label="出库总数量" width="150px" />
        <el-table-column prop="warehouse_name" label="出库仓库" width="200px" />
    </el-table>
    <div style="height: 40px; line-height: 40px;">
        <div style="display: inline-block; float: left;">合计</div>
        <div style="display: inline-block; float:right">销售总数量：{{ sale_total_qty }} &nbsp;&nbsp;&nbsp;
            本次出库产品总数：{{
                outbound_total_qty }}
        </div>
    </div>
    <div class="pagination-wrapper">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
            :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
</template>

<script>
import { ref, reactive, watch, onMounted, computed } from 'vue'
import axios from 'axios'
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
export default {
    props: {
        detailsData: {
            type: String,
            required: true
        },
        orderCode: String
    },
    setup(props) {
        const tableData = ref([])
        const measureOptios = ref([])
        const store = useStore()
        const router = useRouter()
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        const sale_total_qty = computed(() => {
            return tableData.value.reduce((total, row) => {
                return total + (Number(row.pro_sale_qty) || 0)
            }, 0)
        })

        const outbound_total_qty = computed(() => {
            return tableData.value.reduce((total, row) => {
                return total + (Number(row.pro_current_shipment_qty) || 0)
            }, 0)
        })

        onMounted(() => {
            getMeasure()
            fill()
            count()
        })
        // 数据转换方法
        const transformOthwrData = (responseData) => {
            // 1. 添加安全校验
            if (!Array.isArray(responseData)) {
                console.warn('Invalid data passed to transformOthwrData:', responseData)
                return []
            }

            const result = []

            responseData.forEach((mainItem) => {
                // 2. 检查details是否存在且是数组
                const details = Array.isArray(mainItem?.details)
                    ? mainItem.details
                    : []

                let dispatch_qty = 0
                let shipment_qty = 0

                // 3. 安全遍历details
                details.forEach(detail => {
                    dispatch_qty += Number(detail?.pro_awaiting_dispatch_qty) || 0
                    shipment_qty += Number(detail?.pro_current_shipment_qty) || 0
                })

                let auditStatusText = ''
                switch (mainItem?.sale_outbound_status) {
                    case 0: auditStatusText = '待出库'; break
                    case 1: auditStatusText = '部分出库'; break
                    case 2: auditStatusText = '全部出库'; break
                    default: auditStatusText = '未知状态'
                }

                // 4. 处理空details情况（防止表格无数据）
                if (details.length === 0) {
                    result.push({
                        warehouse_name: mainItem.warehouse_name || '',
                        sale_outbound_id: mainItem.sale_outbound_id || '',
                        dispatch_qty,
                        shipment_qty,
                        sale_outbound_status: auditStatusText,
                        sale_order_id: mainItem.sale_order_id || '',
                        sale_order_code: mainItem.sale_order_code || '',
                        sale_outbound_code: mainItem.sale_outbound_code || '',
                        customer_name: mainItem.customer_name || '',
                        sale_order_name: mainItem.sale_order_name || '',
                        // 添加空值占位
                        pro_name: '无产品数据',
                        pro_code: '',
                        pro_brand: '',
                        pro_model: '',
                        measure_id: null,
                        pro_sale_qty: 0,
                        pro_awaiting_dispatch_qty: 0,
                        pro_current_shipment_qty: 0
                    })
                } else {
                    // 5. 正常处理details
                    details.forEach((detail) => {
                        result.push({
                            warehouse_name: mainItem.warehouse_name || '',
                            sale_outbound_id: mainItem.sale_outbound_id || '',
                            dispatch_qty,
                            shipment_qty,
                            sale_outbound_status: auditStatusText,
                            sale_order_id: mainItem.sale_order_id || '',
                            sale_order_code: mainItem.sale_order_code || '',
                            sale_outbound_code: mainItem.sale_outbound_code || '',
                            customer_name: mainItem.customer_name || '',
                            sale_order_name: mainItem.sale_order_name || '',
                            pro_name: detail.pro_name || '',
                            pro_code: detail.pro_code || '',
                            pro_brand: detail.pro_brand || '',
                            pro_model: detail.pro_model || '',
                            measure_id: detail.measure_id || null,
                            pro_sale_qty: detail.pro_sale_qty || 0,
                            pro_awaiting_dispatch_qty: detail.pro_awaiting_dispatch_qty || 0,
                            pro_current_shipment_qty: detail.pro_current_shipment_qty || 0
                        })
                    })
                }
            })

            return result
        }

        // 合并单元格逻辑
        const objectSpanMethod = ({ row, column, rowIndex }) => {
            // 需要合并的字段
            const fieldsToMerge = [
                'sale_outbound_code',
                'sale_outbound_status',
                'customer_name',
                'sale_order_name',
                'dispatch_qty',
                'shipment_qty',
                'warehouse_name'
            ];

            // 不需要合并的列直接返回
            if (!fieldsToMerge.includes(column.property)) {
                return { rowspan: 1, colspan: 1 };
            }

            // 使用订单编号作为分组依据
            const currentGroup = row.sale_outbound_code;

            // 情况1：当前行是表格第一行 或 与前一行不属于同一订单
            if (rowIndex === 0 || tableData.value[rowIndex - 1].sale_outbound_code !== currentGroup) {
                let spanCount = 1;

                // 向后查找相同订单的行数
                while (
                    rowIndex + spanCount < tableData.value.length &&
                    tableData.value[rowIndex + spanCount].sale_outbound_code === currentGroup
                ) {
                    spanCount++;
                }

                // 如果是操作列，需要特殊处理（合并所有同订单的行）
                if (column.property === 'action') {
                    return { rowspan: spanCount, colspan: 1 };
                }

                // 其他合并列检查值是否相同
                let sameValueCount = 1;
                while (
                    rowIndex + sameValueCount < tableData.value.length &&
                    tableData.value[rowIndex + sameValueCount].sale_outbound_code === currentGroup &&
                    tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
                ) {
                    sameValueCount++;
                }

                return sameValueCount > 1
                    ? { rowspan: sameValueCount, colspan: 1 }
                    : { rowspan: 1, colspan: 1 };
            }
            // 情况2：与前一行同订单且同值，需要隐藏单元格
            else if (
                tableData.value[rowIndex - 1].sale_outbound_code === currentGroup &&
                tableData.value[rowIndex - 1][column.property] === row[column.property]
            ) {
                return { rowspan: 0, colspan: 0 };
            }
            // 情况3：同订单内新值的起始位置
            else {
                let sameValueCount = 1;

                while (
                    rowIndex + sameValueCount < tableData.value.length &&
                    tableData.value[rowIndex + sameValueCount].sale_outbound_code === currentGroup &&
                    tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
                ) {
                    sameValueCount++;
                }

                return sameValueCount > 1
                    ? { rowspan: sameValueCount, colspan: 1 }
                    : { rowspan: 1, colspan: 1 };
            }
        };

        //查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //根据计量单位id返回计量单位名称
        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        function infoPage(row) {
            store.commit("SalesOutboundCode", row)
            router.push("/main/Sinv/SalesOutboundInfo")
        }

        function fill() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Outbound/GetSinv_Sale_Outbound_Infos", {
                params: {
                    currentPage: currentPage.value,
                    pageSize: pageSize.value,
                    customerName: '',
                    orderCode: props.detailsData,
                    orderStatus: -1,
                    auditStatus: '1'
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                tableData.value = transformOthwrData(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        function count() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Outbound/Sinv_Sale_OutboundCount", {
                params: {
                    customerName: '',
                    orderCode: props.detailsData
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            fill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            fill();
        }

        return {
            objectSpanMethod, tableData, measureOptios, measureValue, sale_total_qty, outbound_total_qty, infoPage, currentPage, pageCount, pageSize
            , handleSizeChange, handleCurrentChange
        }
    }
}
</script>

<style scoped>
.pagination-wrapper {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    margin-top: 20px;
    /* 与表格的间距 */
}
</style>